package com.aiyige.city.service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.aiyige.BuildConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.city.util.CityUtil;
import com.aiyige.setup.service.UpdateSetupService;
import com.aiyige.utils.PreferenceUtil;

import okhttp3.ResponseBody;
import retrofit2.Response;
import timber.log.Timber;


/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 * TODO: Customize class - update intent actions and extra parameters.
 */
public class UpdateCityService extends IntentService {


    public UpdateCityService() {
        super("UpdateCityService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        PreferenceUtil.putLong(CityUtil.PREF_KEY_LAST_UPDATE_CITY_TIMESTAMP, System.currentTimeMillis());
        String md5 = CityUtil.getCityFileHash();
        if (TextUtils.isEmpty(md5)) {
            md5 = "";
        }

        try {
            Response<ResponseBody> response = ApiManager.getService().allCity(BuildConfig.appVersion, md5).execute();
            if (response.code() == ResponseCode.OK) {
                CityUtil.copyCityFromServer(response);
                CityUtil.populateCityList();
            }
        } catch (Exception e) {
            Timber.e("onHandleIntent:" + Log.getStackTraceString(e));
        }
    }

    public static void updateCity(Context context) {
        context.startService(new Intent(context, UpdateSetupService.class));
    }
}
